﻿using System;
using System.IO;
using Chevron.OrderDetails.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Chevron.OrderDetails.Parser
{
    public static class LabWorksImporter
    {
        public static LabOrdersList ParseLabWorksOrder(string filename, TestCatalog catalog,
                                                       PhysiciansCatalog physicians)
        {
            using (var fs = new FileStream(filename, FileMode.Open))
            {
                return ParseLabWorksOrder(fs, catalog, physicians);
            }
        }

        public static LabOrdersList ParseLabWorksOrder(Stream input, TestCatalog catalog, PhysiciansCatalog physicians)
        {
            var list = new LabOrdersList();
            using (var sr = new StreamReader(input))
            {
                using (var tr = new JsonTextReader(sr))
                {
                    var serializer = new JsonSerializer();
                    var ordersArray = serializer.Deserialize<JArray>(tr);
                    foreach (JObject orderObj in ordersArray)
                    {
                        try
                        {
                            var order = new OrderDto();
                            order.Deserialize(orderObj, physicians, catalog);
                            list.Add(order);
                        }
                        catch
                        {
                            // ignore all
                        }
                    }
                }
            }

            return list;
        }
    }
}